<template>
  <div class="app-container">
    <div class="custom-tree-container">
      <div class="block">
        <el-tree
          v-loading="listLoading"
          :data="locale"
          node-key="id"
          :highlight-current="true"
          default-expand-all
          :props="{children:'child'}"
          :expand-on-click-node="false"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span> <i class="el-icon-location" />{{ data.name }}</span>
            <el-button
              v-if="data.child.length==0"
              icon="el-icon-set-up"
              type="text"
              size="mini"
              @click="() => handleDistributeRoles(data)"
            >
              设备分配
            </el-button>
          </span>
        </el-tree>
      </div>
      <el-dialog :visible.sync="dialogPvVisible" title="设备分配">
        <div style="text-align: center">
          <el-transfer
            v-model="value.roles"
            style="text-align: left; display: inline-block"
            :render-content="renderFunc"
            :titles="['设备列表', '分配设备']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            :data="roles"
            @change="handleChange"
          />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmData(value)">确认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listUnAllocDeviceByLocaleId, listAllocDeviceByLocaleId, allocDevice } from '@/api/alloction/alloction-device'
import { listLocale } from '@/api/info/monitor-point'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  name: 'DeviceAlloction',
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      renderFunc(h, option) {
        return <span>{ option.key } - { option.label }</span>
      },
      value: {
        roles: [],
        localeId: ''
      }, // 已选设备
      roles: [], // 所有设备
      curData: {},
      locale: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: '1', text: '启用' }, { key: '0', text: '禁用' }],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    confirmData(value) {
      this.listLoading = true
      allocDevice({ 'deviceIds': value.roles, 'localeId': value.localeId }).then(() => {
        // const index = this.list.findIndex(v => v.id === this.temp.id)
        // this.list.splice(index, 1, this.temp)
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: '设备分配成功',
          type: 'success',
          duration: 2000
        })
        this.dialogPvVisible = false
      })
    },
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    handleDistributeRoles(row) {
      this.listLoading = true
      // 未被其他区域选中的设备列表
      this.listUnAllocDeviceByLocaleId({ localeId: row.id })
      // 获取此区域已选设备列表
      listAllocDeviceByLocaleId({ localeId: row.id }).then(response => {
        const { data } = response
        const result = data || []
        const roles = []
        result.forEach(item => {
          roles.push(item.id)
        })
        this.value.roles = roles
        this.value = {
          roles: roles,
          localeId: row.id
        }
        this.listLoading = false
      })
      this.dialogStatus = 'distribute'
      this.dialogPvVisible = true
    },
    listUnAllocDeviceByLocaleId(param) {
      const roles = []
      listUnAllocDeviceByLocaleId(param).then(response => {
        const { data } = response
        const result = data || []
        result.forEach(item => {
          roles.push({
            key: item.id,
            label: item.sn
          })
        })
      })
      this.roles = roles
    },
    getList() {
      this.listLoading = true
      listLocale({}).then(response => {
        const { data } = response
        this.locale = JSON.parse(JSON.stringify(data))
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>

